package com.tg.app.activity.device.add;

import android.Manifest;
import android.content.Intent;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.widget.ImageButton;
import android.widget.TextView;

import androidx.annotation.DrawableRes;
import androidx.annotation.Nullable;
import androidx.constraintlayout.widget.ConstraintLayout;
import androidx.fragment.app.Fragment;

import com.appbase.custom.config.ApiUrl;
import com.base.BaseActivity;
import com.tange.feature.data.structure.DeviceTypeBean;
import com.tange.module.core.wifi.scan.ApScanConfiguration;
import com.tange.module.core.wifi.scan.BizWiFiUtil;
import com.tange.module.qrcode.scan.QrCodeScanConstants;
import com.tange.module.qrcode.scan.QrcodeScanActivity;
import com.tg.app.R;
import com.tg.app.activity.device.DeviceListActivity;
import com.tg.app.activity.device.NoDeviceActivity;
import com.tg.app.helper.ActivityHelper;
import com.tg.app.listener.OnAddDeviceListener;
import com.tg.app.report.DeviceAddReport;
import com.tg.app.report.DeviceAddReportBean;
import com.tg.app.util.LogUtils;
import com.tange.base.toolkit.StatusNavUtils;
import com.tange.base.toolkit.StringUtils;
import com.tg.appcommon.android.TGApplicationBase;
import com.tg.appcommon.android.TGLog;
import com.tg.data.helper.DeviceTypeHelper;
import com.tg.network.http.TimeZoneUtils;

import java.util.List;


/**
 * A simple {@link Fragment} subclass.
 * Activities that contain this fragment must implement the
 * create an instance of this fragment.
 *
 * TODO: 拆
 */
public class ScanQrcodeActivity extends BaseActivity implements OnAddDeviceListener {
    private static final String TAG = "ScanQrcodeActivity";
    public static final String EXT_DEVICE_ADD_TYPE = "ext_add_device_type";
    public static final String EXT_DEVICE_ADD_UUID = "ext_add_device_uuid";
    public static final String EXT_DEVICE_ADD_QRCODE_SUCCEDD_ID = "ext_add_device_succeed_ID";
    public static final String EXT_FROM_HISTROY = "device_from_histroy";
    public static final String EXT_FROM_SCAN_EX = "device_from_scan_ex";
    public static final int DEVICE_ADD_TYPE_QRCODE_SCAN = 0x05;
    public static final String EXT_FROM_RESET = "reset";
    public static final String EXT_FROM_SHOULD_RESET = "device_should_reset";
    public static final int DEVICE_ADD_4G_CAR = 0x07;
    public static final int DEVICE_ADD_4G_CAR_SEARCH = 0x08;
    public static final int TYPE_SCAN_QRCODE = 0x12;
    public static final int TYPE_SCAN_4G = 0x13;
    private int originType;
    private ImageButton backButton;
    private ImageButton mRightButton;
    private TextView mRightText;
    private String uuid;
    private long deviceId;
    public static final String EXT_SIM_FREE_COMBO = "sim_NOTICE";
    private int mFreeCombo = 1;
    private String mThirdPartyUUID = "";
    private String from;
    private int statusBarHeight = 0;
    private String mDeviceType;

    private final static String[] needQrcodeScanPermissions = {
            Manifest.permission.CAMERA
    };

    public ImageButton getBackButton() {
        return backButton;
    }

    public ImageButton getRightButton() {
        return mRightButton;
    }

    public void showRightOfToolbar(boolean show){
        if (mRightButton != null){
            mRightButton.setVisibility(show? View.VISIBLE : View.GONE);
        }

        if (mRightText != null){
            mRightText.setVisibility(show? View.VISIBLE : View.GONE);
        }
    }

    @Override
    public boolean shouldSetStatusBarColor() {
        return true;
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        requestWindowFeature(Window.FEATURE_NO_TITLE);//remove title bar  即隐藏标题栏

        super.onCreate(savedInstanceState);
        getWindow().setFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON, WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);

        getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_ADJUST_PAN);

        setContentView(R.layout.activity_add_fragment_new);
        hideActionBar();

        mDeviceType = getIntent().getStringExtra(ApSetWifiActivityEx.EXT_DEVICE_TYPE);
        originType = getIntent().getIntExtra(EXT_DEVICE_ADD_TYPE, 0);
        mThirdPartyUUID = getIntent().getStringExtra(EXT_DEVICE_ADD_UUID);
        TGLog.d(TAG, "orginType = " + originType);
        if (savedInstanceState == null) {
            uuid = getIntent().getStringExtra(ApSetWifiActivityEx.EXT_WIFI_UUID);
            from = getIntent().getStringExtra(EXT_FROM_HISTROY);
            DeviceTypeBean deviceTypeBean = getIntent().getParcelableExtra(DeviceTypeBean.DEVICE_TYPE_BEAN);
            if (StringUtils.equals(from, EXT_FROM_SCAN_EX)){
                String wifi = getIntent().getStringExtra(ApSetWifiActivityEx.EXT_WIFI_NETWORD);
                String pwd = getIntent().getStringExtra(ApSetWifiActivityEx.EXT_WIFI_PWD);
                String uid  = getIntent().getStringExtra(ApConnectActivityEx.EXT_BIND_TOKEN);
                onGenerateQRCode(wifi, pwd, uid);
            } else if (StringUtils.equals(from, EXT_FROM_HISTROY) || StringUtils.equals(from, EXT_FROM_RESET)){
                onDeviceConnecting(uuid, 0);
            } else if (StringUtils.equals(from, EXT_FROM_SHOULD_RESET)){
                goToDeviceProgressFragment(uuid, 0, originType, deviceTypeBean);
            } else if (StringUtils.isEmpty(uuid)){
                QrcodeScanActivity.launch(this);
            }else{
                Reset4gCarGuideNewFragment add4gCarFailedFragment = Reset4gCarGuideNewFragment.newInstance(uuid);
                add4gCarFailedFragment.setOnAddDeviceListener(this);
                getSupportFragmentManager().beginTransaction().add(R.id.fl_lan_add_container, add4gCarFailedFragment, "Reset4gCarGuideNewFragment").commit();
            }
        }

        initView();
        LogUtils.matTrackCustomKVEvent(this, "device_add", "ADW");
        TimeZoneUtils.setUserTimezone();
    }


    @Override
    protected void initView() {
        getStatusBarHeight();

        backButton = findViewById(R.id.back_toolbar_btn);
        mRightText = findViewById(R.id.text_toolbar_right);
        mRightButton = findViewById(R.id.back_toolbar_btn_right);
        backButton.setOnClickListener(view -> {
            TGLog.d("=================== finish ");
            AddDeviceReportHelper.onEventClickByName(TAG, "back_left_text");
            finish();
        });

        ConstraintLayout.LayoutParams lp = (ConstraintLayout.LayoutParams) backButton.getLayoutParams();
        lp.topMargin = statusBarHeight;
        backButton.setLayoutParams(lp);
    }

    private void getStatusBarHeight() {
        statusBarHeight = (int) getResources().getDimension(R.dimen.status_bar_height);
        //获取status_bar_height资源的ID
        int resourceId = getResources().getIdentifier("status_bar_height", "dimen", "android");
        if (resourceId > 0) {
            //根据资源ID获取响应的尺寸值
            statusBarHeight = getResources().getDimensionPixelSize(resourceId);
        }
    }


    public void setBackButtonTop(int topMargin){
        if (getBackButton() != null){
            ConstraintLayout.LayoutParams params = (ConstraintLayout.LayoutParams) getBackButton().getLayoutParams();
            params.topMargin = topMargin;
            getBackButton().setLayoutParams(params);
        }
    }
    public void setToolbar(@DrawableRes int resId, String title) {
        StatusNavUtils.setTranslucentStatus(this);
        if (getBackButton() != null){
            getBackButton().setImageResource(resId);
        }

        showRightOfToolbar(true);
        if (getRightButton() != null){
            getRightButton().setOnClickListener(v -> {
                AddDeviceReportHelper.onEventClickByName(TAG,"back_right_btn");
                ActivityHelper.gotoAddDeviceHomePage(ScanQrcodeActivity.this);
                finish();
            });
        }

        if (mRightText != null){
            if (!StringUtils.isEmpty(title)){
                mRightText.setText(title);
            }
            mRightText.setOnClickListener(v -> {
                AddDeviceReportHelper.onEventClickByName(TAG, "back_right_text");
                ActivityHelper.gotoAddDeviceHomePage(ScanQrcodeActivity.this);

                Fragment f = getSupportFragmentManager().findFragmentByTag(QRCodeImageFragment.TAG);
                if (f != null && f instanceof QRCodeImageFragment && f.isVisible()) {
                    TGLog.i(TAG, "setToolbar: no need to finish activity, because showing QRCodeImageFragment");
                } else {
                    finish();
                }
            });
        }
    }

    @Override
    public void onNoSoundBtnForDevice() {
        if (originType == DEVICE_ADD_4G_CAR||originType == DEVICE_ADD_TYPE_QRCODE_SCAN||originType == DEVICE_ADD_4G_CAR_SEARCH){
            Reset4gCarGuideFragment reset4gCarGuideFragment = Reset4gCarGuideFragment.newInstance(originType);
            reset4gCarGuideFragment.setOnAddDeviceListener(this);
            getSupportFragmentManager().beginTransaction()
                    .add(R.id.fl_lan_add_container, reset4gCarGuideFragment,
                            "Reset4gCarGuideFragment").commit();
        }
    }

    @Override
    public void onClickBtnForDevice() {
        if (backButton.getVisibility() != View.VISIBLE) {
            backButton.setVisibility(View.VISIBLE);
        }
        if (originType == DEVICE_ADD_TYPE_QRCODE_SCAN || originType == DEVICE_ADD_4G_CAR) {
            if (originType == DEVICE_ADD_TYPE_QRCODE_SCAN && !StringUtils.isEmpty(mThirdPartyUUID) && mThirdPartyUUID.length() == 12){
                onDeviceConnecting(mThirdPartyUUID, AddFragmentTabActivity.TYPE_SCAN_QRCODE);
            }else{
                QrcodeScanActivity.launch(this);
            }
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);

        if (requestCode == QrCodeScanConstants.QRCODE_SCAN_REQUEST_CODE) {
            TGApplicationBase.getInstance().putGlobalObject(TGApplicationBase.ADD_DEVICE_FROM, ActivityHelper.ADD_DEVICE_FROM_SCAN_QRCODE);

            if (resultCode == RESULT_OK && data != null) {
                String result = data.getStringExtra(QrCodeScanConstants.QRCODE_SCAN_CONTENT);
                onScanQRCodeSuccess(result);
            } else if (resultCode == RESULT_CANCELED) {
                finish();
            }
        }
    }

    public void onScanQRCodeSuccess(String result) {
        TGLog.d(" onScanQRCodeSuccess result :%s", result);
        if (!TextUtils.isEmpty(result) && (result.length() == 12)) {
            onDeviceConnecting(result, ScanQrcodeActivity.TYPE_SCAN_QRCODE);
        } else {
            ActivityHelper.goToDisScanDeviceActivity(this);
        }
    }


    @Override
    public void onClickTimeout(){
        this.onDeviceConnecting(uuid, TYPE_SCAN_4G);
    }

    @Override
    public void onSearchDevice(Bundle args) {
        args.putInt(EXT_DEVICE_ADD_TYPE, originType);
        SearchConnectFragment searchConnectFragment = SearchConnectFragment.newInstance(args);
        searchConnectFragment.setListener(this);
        getSupportFragmentManager().beginTransaction()
                .replace(R.id.fl_lan_add_container, searchConnectFragment,
                        SearchConnectFragment.TAG).commitAllowingStateLoss();
        hideLoading();
    }

    @Override
    public void onSearchDeviceBegin() {
        showLoading(getString(R.string.find_device));
    }

    @Override
    public void onSearchFailed() {
        hideLoading();
        LogUtils.matTrackCustomKVEvent(this, "event_add", "有线添加搜索失败");
    }

    @Override
    public void onSetDeviceName(long device, String uuid, int authStatus, String iccId,int freeCombo) {
        onAddDeviceReport();
        mFreeCombo = 0;
        if (originType == DEVICE_ADD_4G_CAR||originType == DEVICE_ADD_TYPE_QRCODE_SCAN||originType == DEVICE_ADD_4G_CAR_SEARCH){
            setDeviceName(device, uuid, authStatus, iccId,freeCombo);
        }else{
            hideLoading();
            backButton.setVisibility(View.GONE);
            this.uuid = uuid;
            this.deviceId = device;
            int authStatus1 = (originType == DEVICE_ADD_TYPE_QRCODE_SCAN) ? authStatus : 0;
            SetDeviceNameFragment setDeviceNameFragment = SetDeviceNameFragment.newInstance(device, uuid, authStatus1, iccId);
            setDeviceNameFragment.setListener(this);
            getSupportFragmentManager().beginTransaction()
                    .replace(R.id.fl_lan_add_container, setDeviceNameFragment,
                            setDeviceNameFragment.TAG).commitAllowingStateLoss();
        }

    }

    @Override
    public void onSet4GDeviceName(long device, String uuid, int authStatus, String iccId,int freeCombo) {
        onAddDeviceReport();
        mFreeCombo = 0;
        setDeviceName(device, uuid, authStatus, iccId,freeCombo);

    }


    private void setDeviceName(long device, String uuid, int authStatus, String iccId, int freeCombo) {
        String wifi = ApScanConfiguration.INSTANCE.apNamePrefix() + "_" + uuid;
        TGLog.d(TAG + " wifi = " + wifi);
        BizWiFiUtil.removeDeviceWifi();

        Intent intent = new Intent(getBaseContext(), ApSetNameActivity.class);
        intent.putExtra(ApiUrl.DEVICEID, device);
        intent.putExtra(ApiUrl.DEVICE_UUID, uuid);
        intent.putExtra(ApiUrl.DEVICE_AUTH, authStatus);
        intent.putExtra(ApiUrl.DEVICE_TYPE, DeviceTypeHelper.DEVICE_DRSIM);
        intent.putExtra(ApiUrl.DEVICE_ICCID, iccId);
        intent.putExtra(EXT_SIM_FREE_COMBO,freeCombo);
        startActivity(intent);
        finish();
    }

    @Override
    public void onFinish(boolean isApLocal) {
        Intent intent = new Intent();
        if (!isApLocal) {
            intent.setClass(getBaseContext(), DeviceListActivity.class);
            intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK | Intent.FLAG_ACTIVITY_NEW_TASK);
            if (originType == DEVICE_ADD_TYPE_QRCODE_SCAN && mFreeCombo ==0) {
                intent.putExtra(EXT_DEVICE_ADD_QRCODE_SUCCEDD_ID, this.deviceId);
            }
        }
        startActivity(intent);
        finish();
    }

    @Override
    public void onApSearchLoading() {
        backButton.setEnabled(false);
    }

    @Override
    public void onBackPressed() {
        TGLog.d(TAG, "onBackPressed");
    }


    @Override
    public void onGenerateQRCode(String ssi, String pwd, String uuid) {
        QRCodeImageFragment qrCodeImageFragment = QRCodeImageFragment.newInstance(ssi, pwd, uuid, mDeviceType);
        qrCodeImageFragment.setListener(this);
        if (DeviceTypeHelper.isLockBell(mDeviceType)) {
            qrCodeImageFragment.setPlaySound(false);
        }
        getSupportFragmentManager().beginTransaction()
                .replace(R.id.fl_lan_add_container, qrCodeImageFragment,
                        QRCodeImageFragment.TAG).commitAllowingStateLoss();
    }


    @Override
    public void onDeviceConnecting(String random, int type) {
        uuid = random;
        goToDeviceProgressFragment(random, type, originType, null);
    }

    private void goToDeviceProgressFragment(String random, int type, int deviceType, DeviceTypeBean deviceTypeBean){
        if (!TextUtils.isEmpty(random)){
            DeviceAddReportBean bean = DeviceAddReport.getInstance().getReportBean();
            if (bean!=null){
                bean.uuid = random;
                DeviceAddReport.getInstance().setReportBean(bean);
            }
            DeviceProgressFragment deviceProgressFragment;
            if (deviceTypeBean == null){
                deviceProgressFragment = DeviceProgressFragment.newInstance(uuid, type, deviceType);
            }else{
                deviceProgressFragment = DeviceProgressFragment.newInstance(uuid, type, deviceTypeBean);
            }

            deviceProgressFragment.setListener(this);
            getSupportFragmentManager().beginTransaction().replace(R.id.fl_lan_add_container, deviceProgressFragment, DeviceProgressFragment.TAG).commitAllowingStateLoss();
        }
    }

    @Override
    public void onAddDeviceFailed(int type) {
        onAddDeviceReport();
        backButton.setVisibility(View.GONE);
        ActivityHelper.gotoAddFailedActivity(this, null, uuid, false);

    }
    private void onAddDeviceReport(){
        DeviceAddReportBean  bean = DeviceAddReport.getInstance().getReportBean();
        if (bean!=null){
            bean.connectLoadEnd  = System.currentTimeMillis();
        }
    }
}
